package com.alex.wechat.mp.message.news.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.IpUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.media.entity.MediaTypes;
import com.alex.wechat.mp.message.news.entity.WxNewsItem;
import com.alex.wechat.mp.message.news.entity.WxNewsTemplate;
import com.alex.wechat.mp.message.news.service.WxArticleResolver;
import com.alex.wechat.mp.message.news.service.WxNewsItemServiceI;
import com.alex.wechat.mp.message.news.service.WxNewsTemplateServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;

/**
 * 图文消息
 * 
 */
@Controller
@RequestMapping("/wxNewsTemplateController")
public class WxNewsTemplateController {
  private static final Logger logger = Logger.getLogger(WxNewsTemplateController.class);

  @Autowired
  private WxNewsTemplateServiceI newsTemplateService;
  @Autowired
  private WxNewsItemServiceI newsItemService;
  @Autowired
  private SystemService systemService;
  @Autowired
  private WxMpService wxMpService;
  @Autowired
  private WxArticleResolver articleResolver;

  /**
   * 列表展示
   * 
   * @return
   */
  @RequestMapping(params = "list")
  public ModelAndView list() {
    return new ModelAndView("com/gomore/wechat/mp/message/news/newsTemplateList");
  }

  @RequestMapping(params = "datagrid")
  @ResponseBody
  /**
   * 查询数据
   * 
   * @param newsTemplate
   * @param request
   * @param response
   * @param dataGrid
   */
  public void datagrid(WxNewsTemplate newsTemplate, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {

    CriteriaQuery cq = new CriteriaQuery(WxNewsTemplate.class, dataGrid);
    cq.eq("accountId", WxContext.getOriginalId());
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, newsTemplate);

    this.newsTemplateService.getDataGridReturn(cq, true);

    TagUtil.datagrid(response, dataGrid);
  }

  /**
   * 删除信息模板
   * 
   * @param newsTemplate
   * @param req
   * @return
   */
  @RequestMapping(params = "del")
  @ResponseBody
  public AjaxJson del(WxNewsTemplate newsTemplate, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    newsTemplate = this.newsTemplateService.getEntity(WxNewsTemplate.class, newsTemplate.getId());

    this.newsTemplateService.delete(newsTemplate);

    String message = "删除信息数据成功！";
    systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    j.setMsg(message);
    return j;
  }

  /**
   * 批量删除图文消息
   * 
   * @return
   */
  @RequestMapping(params = "doBatchDel")
  @ResponseBody
  public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();
    String message = "删除信息数据成功";
    int succeed = 0;
    int error = 0;
    try {
      for (String id : ids.split(",")) {
        WxNewsTemplate newsTemplate = this.newsTemplateService.getEntity(WxNewsTemplate.class, id);
        this.newsTemplateService.delete(newsTemplate);
        succeed += 1;
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
      }
    } catch (Exception e) {
      e.printStackTrace();
      error += 1;
      message = "删除信息数据失败";
      throw new BusinessException(e.getMessage());
    }
    message = "删除信息数据成功" + succeed + "条，失败" + error + "条";
    j.setMsg(message);
    return j;
  }

  /**
   * 跳转到信息模板
   * 
   * @param req
   * @return
   */
  @RequestMapping(params = "goEditView")
  public ModelAndView goEditView(HttpServletRequest req) {
    String id = req.getParameter("id");
    req.setAttribute("id", id);
    if (StringUtil.isNotEmpty(id)) {
      WxNewsTemplate newsTemplate = this.newsTemplateService.getEntity(WxNewsTemplate.class, id);
      req.setAttribute("tempateName", newsTemplate.getTemplateName());
    }
    return new ModelAndView("com/gomore/wechat/mp/message/news/newsTemplateInfo");
  }

  @RequestMapping(params = "doSave")
  @ResponseBody
  public AjaxJson doSave(WxNewsTemplate newsTemplate, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    String id = newsTemplate.getId();
    if (StringUtil.isNotEmpty(id)) {
      WxNewsTemplate tempAutoResponse = this.newsTemplateService.getEntity(WxNewsTemplate.class,
          newsTemplate.getId());
      String message = "修改图文模板成功！";
      try {
        MyBeanUtils.copyBeanNotNull2Bean(newsTemplate, tempAutoResponse);
        this.newsTemplateService.saveOrUpdate(tempAutoResponse);
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      } catch (Exception e) {
        e.printStackTrace();
      }

    } else {
      newsTemplate.setCreateDate(new Date());
      String accountId = WxContext.getOriginalId();
      if (!"-1".equals(accountId)) {
        this.newsTemplateService.save(newsTemplate);
      } else {
        j.setSuccess(false);
        j.setMsg("请添加一个公众帐号。");
      }
    }
    return j;
  }

  /**
   * 跳转到消息模板
   * 
   * @param req
   * @return
   */
  @RequestMapping(params = "goNewsItem")
  public ModelAndView goNewsItem(HttpServletRequest req) {
    String templateId = req.getParameter("templateId");
    req.setAttribute("templateId", templateId);

    String id = req.getParameter("id");
    req.setAttribute("id", id);
    if (StringUtil.isNotEmpty(id)) {
      WxNewsItem newsItem = this.newsTemplateService.getEntity(WxNewsItem.class, id);
      req.setAttribute("title", newsItem.getTitle());
      req.setAttribute("content", newsItem.getContent());
      req.setAttribute("author", newsItem.getAuthor());
      req.setAttribute("imagePath", newsItem.getImagePath());
      req.setAttribute("description", newsItem.getDescription());
      req.setAttribute("templateId", newsItem.getNewsTemplate().getId());
      req.setAttribute("orders", newsItem.getOrders());
    } else {
      // 判断是否是头一条短信
      List<WxNewsItem> newsItemList = this.newsTemplateService.findByProperty(WxNewsItem.class,
          "newsTemplate.id", templateId);
      req.setAttribute("orders", (newsItemList.size() + 1));
    }

    return new ModelAndView("com/gomore/wechat/mp/message/news/itemInfo");
  }

  @RequestMapping(params = "jumpupload")
  public ModelAndView jumpUpload(HttpServletRequest req) {
    return new ModelAndView("com/gomore/wechat/mp/message/news/upload");
  }

  /**
   * 保存新增关键字
   * 
   * @param newsItem
   * @param req
   * @return
   */
  @RequestMapping(params = "saveNewsTemplate")
  @ResponseBody
  public AjaxJson saveNewsTemplate(WxNewsItem newsItem, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    String id = newsItem.getId();
    if (StringUtil.isNotEmpty(id)) {
      WxNewsItem tempAutoResponse = this.newsTemplateService.getEntity(WxNewsItem.class,
          newsItem.getId());
      String message = "修改关键字回复成功！";
      try {
        MyBeanUtils.copyBeanNotNull2Bean(newsItem, tempAutoResponse);
        this.newsItemService.saveOrUpdate(tempAutoResponse);
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      } catch (Exception e) {
        logger.error("", e);
        j.setSuccess(false);
        j.setMsg("保存失败: " + e.getMessage());
      }
    } else {
      String templateId = req.getParameter("templateId");
      WxNewsTemplate newsTemplate = this.newsTemplateService.getEntity(WxNewsTemplate.class,
          templateId);
      newsItem.setNewsTemplate(newsTemplate);
      this.newsItemService.save(newsItem);
    }
    return j;
  }

  /**
   * 批量上传微信多媒体素材
   * 
   * @return
   */
  @RequestMapping(params = "doBatchUpload")
  @ResponseBody
  public AjaxJson doBatchUpload(String ids, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "微信图文素材上传成功";
    try {
      for (String id : ids.split(",")) {
        uploadMediaOne(id, request);
        systemService.addLog(message + ",id=" + id, Globals.Log_Type_INSERT,
            Globals.Log_Leavel_INFO);
      }
    } catch (Exception e) {
      logger.error("", e);
      message = "微信图文素材上传失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  @Transactional
  private void uploadMediaOne(String id, HttpServletRequest request) throws Exception {
    WxNewsTemplate newsTemplate = newsTemplateService.getEntity(WxNewsTemplate.class, id);
    if (newsTemplate == null) {
      return;
    }

    WxMpMaterialNews news = new WxMpMaterialNews();
    for (WxNewsItem item : newsTemplate.getNewsItemList()) {
      // 上传缩略图
      uploadAtricleCover(item);

      // 上传正文
      WxMpMaterialNews.WxMpMaterialNewsArticle article = new WxMpMaterialNews.WxMpMaterialNewsArticle();
      article.setTitle(item.getTitle());
      article.setAuthor(item.getAuthor());
      article.setThumbMediaId(item.getThumbMediaId());
      article.setDigest(item.getDescription());
      article.setShowCoverPic(true);
      article.setContent(articleResolver.resolve(item.getContent()));
      String contentUrl = IpUtil.getDomain(request) + "/wxNewsItemController.do?goContent&id="
          + item.getId();
      article.setContentSourceUrl(contentUrl);
      news.addArticle(article);
    }

    WxMpMaterialUploadResult res = wxMpService.getMaterialService().materialNewsUpload(news);
    newsTemplate.setMediaId(res.getMediaId());
    newsTemplateService.saveOrUpdate(newsTemplate);
  }

  /**
   * 上传单个文章的封面
   * 
   * @param item
   * @throws WxErrorException
   */
  private void uploadAtricleCover(WxNewsItem item) throws WxErrorException {
    WxMpMaterial wxMaterial = new WxMpMaterial();
    File coverFile = new File(item.getRealPath());
    wxMaterial.setFile(coverFile);
    wxMaterial.setName(coverFile.getName());
    WxMpMaterialUploadResult res = wxMpService.getMaterialService()
        .materialFileUpload(MediaTypes.THUMB, wxMaterial);
    item.setThumbMediaId(res.getMediaId());
    item.setThumbUrl(res.getUrl());
    newsItemService.saveOrUpdate(item);
  }
}